import { Button, Form, Input, Popconfirm, Table, message } from 'antd';
import React, { useContext, useEffect, useRef, useState, createContext } from 'react';
import http from '../../api'

const EditableContext = createContext(null);
const Provider = EditableContext.Provider

const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <Provider value={form}>
                <tr {...props} />
            </Provider>
        </Form>
    );
};

const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);

    useEffect(() => {
        if (editing) {
            inputRef.current.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({
            [dataIndex]: record[dataIndex],
        });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({
                ...record,
                ...values,
            });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;
    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{
                    margin: 0,
                }}
                name={dataIndex}
                rules={[
                    {
                        required: true,
                        message: `${title} is required.`,
                    },
                ]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{
                    paddingRight: 24,
                }}
                onClick={toggleEdit}
            >
                {children}
            </div>
        );
    }
    return <td {...restProps}>{childNode}</td>;
};
export default function NewsCategory() {
    const [dataSource, setDataSource] = useState();

    useEffect(() => {
        getTableList()
    }, [])

    /**
     * 获取新闻分类列表
     */
    const getTableList = () => {
        http.get('/categories').then(res => {
            setDataSource(res.data)
        })
    }

    /**
     * 删除新闻分类
     */
    const delOk = (item) => {
        http.delete(`/categories/${item.id}`).then(res => {
            getTableList()
            message.info('删除成功')
        })
    }

    const defaultColumns = [
        {
            title: 'ID',
            dataIndex: 'id',
            width: '30%',
        },
        {
            title: '栏目名称',
            dataIndex: 'title',
            editable: true
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) =>
                dataSource.length >= 1 ? (
                    <Popconfirm title="确定要删除么?" okText="确认" cancelText="取消" onConfirm={() => delOk(record)}>
                        <a>删除</a>
                    </Popconfirm >
                ) : null,
        },
    ];
    const handleSave = (row) => {
        http.patch(`/categories/${row.id}`, {
            title: row.title,
            value: row.title
        }).then(res => {
            getTableList()
            message.success('修改成功')
        })
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });
    return (
        <div>
            <h2>新闻分类</h2>
            <Table
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                columns={columns}
            />
        </div>
    );
};